package com.ganzi.manager.conf;

import com.ganzi.manager.exception.GlobalExceptionHandler;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;

@Configuration
@Primary
public class WebConfig implements WebMvcConfigurer {

    @Value("${temp.tmepPath}")
    private String tmepPath;
    /**全局异常*/
    @Bean
    GlobalExceptionHandler getGlobalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

    /**配置mybatis的分页插件pageHelper*/
    @Bean
    public PageHelper pageHelper(){
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum","true");
        properties.setProperty("rowBoundsWithCount","true");
        properties.setProperty("reasonable","true");
        properties.setProperty("dialect","mysql");    //配置mysql数据库的方言
        pageHelper.setProperties(properties);
        return pageHelper;
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation(tmepPath);
        return factory.createMultipartConfig();
    }

    /**
     * 添加拦截器，可以做权限管理相关
     * */
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        ArrayList<String> commonPathPatterns = getExcludeCommonPathPatterns();
//        registry.addInterceptor(getServiceAuthRestInterceptor()).addPathPatterns("/**").excludePathPatterns(commonPathPatterns.toArray(new String[]{}));
//        commonPathPatterns.add("/api/user/validate");
//        registry.addInterceptor(getCustomerAuthRestInterceptor()).addPathPatterns("/**").excludePathPatterns(commonPathPatterns.toArray(new String[]{}));
//        super.addInterceptors(registry);
//    }


    /**
     * 需要排除的路径
     * */
    private ArrayList<String> getExcludeCommonPathPatterns() {
        ArrayList<String> list = new ArrayList<>();
        String[] urls = {
                "/v2/api-docs",
                "/swagger-resources/**",
                "/cache/**",
                "/api/log/save",
                "/error"     //添加拦截过滤 不拦截springboot 默认错误 /error
        };
        Collections.addAll(list, urls);
        return list;
    }
}
